﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using Newtonsoft.Json;

using BOSS.Domain;

namespace BOSS.Web.Extensions
{
    /// <summary>
    /// HtmlHelper 扩展
    /// </summary>
    public static class JsonExtensions
    {
        private class DefaultJson
        {
            public bool success { get; set; }

            public int totalCount { get; set; }

            public object data { get; set; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <returns></returns>
        public static string ToJson(this HtmlHelper htmlHelper, object data)
        {
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            };

            return JsonConvert.SerializeObject(data, Formatting.Indented, setting);
        }

        public static string ToJson(this HtmlHelper htmlHelper, object data, IDictionary<string, string> extendsions )
        {
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            };

            string json = JsonConvert.SerializeObject(data, Formatting.Indented, setting);

            foreach (var key in extendsions.Keys)
            {
                string[] keys = key.Split('.');

                int startIndex = 0;
                string temp = json;
                foreach (var item in keys)
                {
                    if (json.Contains("\"" + item + "\""))
                    {
                        startIndex = temp.IndexOf(item);
                        temp = temp.Substring(startIndex - 1);
                    }    
                }


            }

            return json;
        }
    }
}
